package com.hxkj.cst.chengshuitong.ui.activity

import android.app.Activity
import android.content.Intent
import android.content.res.TypedArray
import android.os.Build
import android.os.Bundle
import android.util.SparseArray
import android.view.View
import android.widget.ImageView
import com.hxkj.cst.chengshuitong.R
import com.hxkj.cst.chengshuitong.getDataFromShared
import com.hxkj.cst.chengshuitong.setDataToShared
import com.hxkj.cst.chengshuitong.ui.adapter.GuidePageAdapter
import kotlinx.android.synthetic.main.activity_launcher.*


/**
 * 作者： Luoyang on 2017/5/25.
 * 描述： 启动页面
 */
class LauncherActivity : Activity() {
    /*
    * 存放引导页资源容器的集合
    * */
    var mSpareArray: SparseArray<ImageView>? = SparseArray()

    val INSTALL_STATE = "install"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_launcher)

        /*
        * 检查是否是第一次安装
        * true:加载并暂时引导图片
        * false:跳转主页
        * */
        val isInstall = getDataFromShared(INSTALL_STATE, false) as Boolean
        if (isInstall) {
            startActivity(Intent(this, MainActivity::class.java))
            finish()
        } else {
            initLauncherImages()
            mSpareArray?.let { launcher_viewpager.adapter = GuidePageAdapter(it) }
            setDataToShared(INSTALL_STATE, true)
        }
    }

    /*
    * 设置全屏沉浸式展示引导图片
    * */
    override fun onWindowFocusChanged(hasFocus: Boolean) {
        super.onWindowFocusChanged(hasFocus)
        if (hasFocus && Build.VERSION.SDK_INT >= 19) {
            val decorView = window.decorView
            decorView.systemUiVisibility =
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE or
                            View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or
                            View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or
                            View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or
                            View.SYSTEM_UI_FLAG_FULLSCREEN or
                            View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
        }
    }

    /*
    * 初始化引导图片资源
    * */
    fun initLauncherImages() {
        val typeArray: TypedArray = resources.obtainTypedArray(R.array.Launcher_Images)
        for (index in 0 until typeArray.length()) {
            val imageView = createImageView(typeArray.getResourceId(index, R.mipmap.ic_launcher))
            if (index == typeArray.length() - 1)
                imageView.setOnClickListener {
                    startActivity(Intent(this, MainActivity::class.java))
                    finish()
                }
            mSpareArray?.put(index, imageView)
        }
        typeArray.recycle()
    }

    /*
    * 创建展示引导图片资源的容器 并放在Spare集合中供ViewPager使用
    * */
    fun createImageView(resourceId: Int): ImageView {
        val imageView: ImageView = ImageView(this)
        imageView.scaleType = ImageView.ScaleType.FIT_XY
        imageView.setImageResource(resourceId)
        return imageView
    }
}